﻿using System;
using System.IO;
using NDbUnit.Core;
using NDbUnit.Core.SqlClient;
using NUnit.Framework;

namespace ActivateYourGlutes.Model.Tests.Integration
{
    public class DatabaseIntegrationTest
    {
        protected NDbUnitTest Database { get; private set; }

        [TestFixtureSetUp]
        public void FixtureSetup()
        {
            const string connectionString = "Data Source=(local);Initial Catalog=ActivateYourGlutes_TestDb;Integrated Security=True;MultipleActiveResultSets=True";
            Database = new SqlDbUnitTest(connectionString);
        }

        [TestFixtureTearDown]
        public void FixtureTearDown()
        {
            Database.PerformDbOperation(DbOperationFlag.DeleteAll);
        }

        [TearDown]
        public void TearDown()
        {
            Database.PerformDbOperation(DbOperationFlag.DeleteAll);
        }

        /// <summary>
        /// Returns a stream to a test resource. Test resources should be placed in a folder next to the test class named TestResource.
        /// Test resources themselves should be marked as embedded resources. We embed the resources to minimise the number of file system
        /// dependencies of the integration tests.
        /// </summary>
        protected Stream TestResource(string name)
        {
            string fullName = GetType().FullName;
            string className = GetType().Name;
            string resourceNamespace = fullName.Substring(0, fullName.Length - className.Length);
            string resourceName = String.Concat(resourceNamespace, "TestResource.", name);

            Stream resourceStream = GetType().Assembly.GetManifestResourceStream(resourceName);

            if (resourceStream == null)
                throw new TestResourceNotFound();

            return resourceStream;
        }
    }
}